import pandas as pd
import numpy as np

def load_scores_data(file_path='scores.csv'):
    try:
        # 读取CSV文件
        df = pd.read_csv(file_path)
        # 确保学生ID列存在且唯一
        if df.iloc[:, 0].duplicated().any():
            print("警告: 数据中存在重复的学生ID!")
        return df
    except FileNotFoundError:
        print(f"错误: 文件 '{file_path}' 未找到!")
        return None
    except Exception as e:
        print(f"读取文件时发生错误: {e}")
        return None

def calculate_standard_score(score, mean, std):
    if std == 0:  # 防止除以零
        return 500
    z = ((score - mean) / std) * 100 + 500
    # 限制在100-900范围内
    z = max(100, min(900, z))
    # 四舍五入到整数
    return round(z)

def calculate_subject_stats(df, required_subjects, optional_subjects):
    subject_stats = {}
    for subject in required_subjects + optional_subjects:
        if subject in df.columns:
            subject_scores = df[subject].dropna()
            if len(subject_scores) > 0:
                subject_stats[subject] = {
                    'mean': subject_scores.mean(),
                    'std': subject_scores.std(),
                    'count': len(subject_scores)
                }
            else:
                subject_stats[subject] = {
                    'mean': 0,
                    'std': 1,
                    'count': 0
                }
    return subject_stats

def calculate_final_score(student_id):
    # 加载数据
    df = load_scores_data()
    if df is None:
        return None
    
    # 定义必选科目和任选科目
    required_subjects = ['A', 'B', 'C']  # 必选科目
    optional_subjects = ['D', 'E', 'F', 'G', 'H', 'I']  # 任选科目
    
    # 检查学生ID是否存在
    if student_id not in df.iloc[:, 0].values:
        print(f"错误: 学生ID '{student_id}' 不存在!")
        return None
    
    # 提取学生数据
    student_data = df[df.iloc[:, 0] == student_id].iloc[0]
    
    # 找出学生选择的任选科目
    selected_optionals = []
    for subject in optional_subjects:
        if subject in df.columns and not pd.isna(student_data[subject]):
            selected_optionals.append(subject)
    
    # 验证学生选择的科目数量
    if len(selected_optionals) != 3:
        print(f"错误: 学生ID '{student_id}' 选择的任选科目数量不正确!")
        return None
    
    # 计算所有科目的统计数据
    subject_stats = calculate_subject_stats(df, required_subjects, optional_subjects)
    
    # 计算学生各科的标准分
    standard_scores = {}
    for subject in required_subjects + selected_optionals:
        if subject in df.columns and not pd.isna(student_data[subject]):
            score = student_data[subject]
            mean = subject_stats[subject]['mean']
            std = subject_stats[subject]['std']
            standard_scores[subject] = calculate_standard_score(score, mean, std)
    
    # 计算标准分和
    weighted_sum = 0
    for subject in required_subjects:
        if subject in standard_scores:
            weighted_sum += standard_scores[subject] * 1.5
        else:
            print(f"警告: 学生ID '{student_id}' 缺少必选科目 '{subject}' 的成绩!")
            return None
    
    for subject in selected_optionals:
        if subject in standard_scores:
            weighted_sum += standard_scores[subject] * 1.0
        else:
            print(f"警告: 学生ID '{student_id}' 缺少任选科目 '{subject}' 的成绩!")
            return None
    
    # 计算所有有效考生的标准分和
    all_weighted_sums = []
    valid_students = 0
    
    for _, row in df.iterrows():
        # 检查学生是否选择了正确的科目
        valid_student = True
        for subject in required_subjects:
            if subject not in df.columns or pd.isna(row[subject]):
                valid_student = False
                break
        
        if not valid_student:
            continue
        
        student_selected_optionals = []
        for subject in optional_subjects:
            if subject in df.columns and not pd.isna(row[subject]):
                student_selected_optionals.append(subject)
        
        if len(student_selected_optionals) != 3:
            continue
        
        # 计算该学生的标准分和
        student_std_scores = {}
        for subject in required_subjects + student_selected_optionals:
            if subject in df.columns and not pd.isna(row[subject]):
                score = row[subject]
                mean = subject_stats[subject]['mean']
                std = subject_stats[subject]['std']
                student_std_scores[subject] = calculate_standard_score(score, mean, std)
        
        student_weighted_sum = 0
        for subject in required_subjects:
            if subject in student_std_scores:
                student_weighted_sum += student_std_scores[subject] * 1.5
            else:
                valid_student = False
                break
        
        if not valid_student:
            continue
        
        for subject in student_selected_optionals:
            if subject in student_std_scores:
                student_weighted_sum += student_std_scores[subject] * 1.0
            else:
                valid_student = False
                break
        
        if valid_student:
            all_weighted_sums.append(student_weighted_sum)
            valid_students += 1
    
    # 检查是否有足够的有效学生数据
    if valid_students < 2:
        print("错误: 有效学生数据不足，无法计算最终得分!")
        return None
    
    # 计算所有标准分和的平均分和标准差
    weighted_sum_mean = np.mean(all_weighted_sums)
    weighted_sum_std = np.std(all_weighted_sums)
    
    # 计算最终得分
    final_score = calculate_standard_score(weighted_sum, weighted_sum_mean, weighted_sum_std)
    
    return final_score

def main():
    # 读取输入的考生序号
    student_id = input().strip()
    
    # 尝试将输入转换为整数（如果可能）
    try:
        student_id = int(student_id)
    except ValueError:
        pass  # 保持为字符串
    
    # 计算并输出最终得分
    final_score = calculate_final_score(student_id)
    if final_score is not None:
        print(final_score)

if __name__ == "__main__":
    main()

